"use client";

import { Box, Button } from "@chakra-ui/react";
import { useState } from "react";
import { EditIcon } from "../Icons/EditIcon";
import { CheckIcon } from "@/src/icons/CheckIcon";
import { CloseIcon } from "@/src/icons/CloseIcon";

function MacroNameEditor({
  name,
  onChange,
  checkName,
  isDisabled,
  visibility = "visible",
}: {
  name: string;
  onChange: (name: string) => void;
  checkName: (name: string) => boolean;
  isDisabled: boolean;
  visibility?: string;
}) {
  const [edit, setEdit] = useState(false);

  const [editName, setEditName] = useState(name);

  const onEditChange = (evt: any) => {
    const name = evt.target.value;
    setEditName(name);
    const res = checkName(name);
    if (res) {
    }
  };

  const onSubmit = () => {
    onChange(editName == "" ? "未命名" : editName);
    setEdit(false);
  };

  return (
    <Box visibility={visibility as any}>
      {edit ? (
        <Box>
          <form
            onSubmit={onSubmit}
            className="flex gap-2 items-end"
            onKeyDown={(evt) => {
              if (evt.key === "Escape") setEdit(false);
            }}
          >
            <Box className="flex items-baseline gap-4">
              <input
                type="text"
                value={editName}
                onChange={onEditChange}
                autoFocus
                onFocus={(evt) => evt.target.select()}
                maxLength={20}
                placeholder="为宏命名"
                className=" bg-transparent caret-blue-1 outline-none font-medium text-[20px]"
              />
              <Box className="text-[12px] text-gray-500 font-medium">
                {editName.length}/20
              </Box>
            </Box>
            <Box
              onClick={() => {
                setEdit(false);
                setEditName(name);
              }}
            >
              <CloseIcon className="w-6 h-6 hover:fill-blue-1 hover:cursor-pointer" />
            </Box>
            <Box onClick={() => onSubmit()}>
              <CheckIcon className="w-6 h-6 hover:fill-blue-1 hover:cursor-pointer" />
            </Box>
          </form>
        </Box>
      ) : (
        <Box className="flex gap-2 w-fit items-center">
          <Box className="font-medium text-[20px]">
            {name}{" "}
            <span className="text-[12px] text-[#eeeeee] ml-4">
              {name.length}/20
            </span>
          </Box>
          <Box
            onClick={() => {
              setEditName(name);
              setEdit(true);
            }}
            hidden={isDisabled}
            className="hover:cursor-pointer"
          >
            <EditIcon className="w-5 h-5" />
          </Box>
        </Box>
      )}
    </Box>
  );
}

export default MacroNameEditor;
